import subprocess
import time
import socket

def telegram_init():
	global s
	host = ('127.0.0.1', 2391)
	telegram = subprocess.Popen('/home/netsga/tg/telegram-cli -k /home/netsga/tg/tg-server.pub '
		'-P %d' % host[1],
		shell=True,
		stdout=subprocess.PIPE,
		stdin=subprocess.PIPE)
	time.sleep(0.2)

	try:
    		#create an AF_INET, STREAM socket (TCP)
    		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	except socket.error, msg:
    		print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
    		sys.exit();
	print 'Socket Created'

	s.connect(host)
	print 'Connected'
	s.send('dialog_list\n'.encode())
	time.sleep(10)
	reply = s.recv(4096)
	print reply
	#s.send('msg Pp PPOMPPU Bot is started!!!\n'.encode())

def telegram_read():
	global s
	s.send('mark_read Pp\n'.encode())

def telegram_send(msg):
	global s
	s.send('msg Pp ' + msg + '\n'.encode())
	reply = s.recv(4096)
	print reply

def telegram_close():
	global s
	s.send('safe_quit\n'.encode())
	time.sleep(5)
	reply = s.recv(4096)
	s.close()
	print('Socket Closed')
	
